<template>
  <div class="mapBox flex-y-start-stretch mt-15 f1">
    <FirstHeader :title="'实时路线'" :file="'rescue'" :icon="'route-icon'"></FirstHeader>
    <div class="MapContainer p-5">
      <div class="modal">
        <div class="plate flex-x-between">
          <span>川A2056J</span>
          <img src="@/assets/images/rescue/stop.png" alt="" srcset="" />
          <!-- <el-image class="icon" src="/assets/images/rescue/stop.png" fit="contain" /> -->
        </div>
        <div class="item flex-x-start-start">
          <div class="label">定位时间：</div>
          <div class="value">2024-01-04 15:29:25</div>
        </div>
        <div class="item flex-x-start-start">
          <div class="label">行驶速度：</div>
          <div class="value">30km/h</div>
        </div>
        <div class="item flex-x-start-start">
          <div class="label">今日里程：</div>
          <div class="value">48km</div>
        </div>
        <div class="item flex-x-start-start">
          <div class="label">行驶状态：</div>
          <div class="value">在线/停车（0秒）</div>
        </div>
        <div class="item flex-x-start-start">
          <div class="label">地理位置：</div>
          <div class="value">四川省成都市锦江区三圣街道 红星路新房大厦6栋</div>
        </div>
      </div>
      <div class="container" id="container"></div>
      <!-- <div id="panel" class="panel"></div> -->
    </div>
  </div>
  <!-- 起始标记点 -->
  <div class="startMarker" ref="startBox">
    <div>起</div>
    <img src="@/assets/images/rescue/start.png" alt="" srcset="" />
    <!-- <el-image class="icon" src="@/assets/images/rescue/start.png" fit="contain" /> -->
  </div>
  <div class="startMarker" ref="endBox">
    <div>终</div>
    <img src="@/assets/images/rescue/end.png" alt="" srcset="" />
    <!-- <el-image class="icon" src="@/assets/images/rescue/end.png" fit="contain" /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import FirstHeader from "@/components/FirstHeader/index.vue";

// 初始化
//@ts-expect-error 忽略报错
window._AMapSecurityConfig = {
  securityJsCode: "0aae0b0baa5f824a49792fc2c44fe022" //申请key时的安全密钥
};
let map: any = null;
let AMap: any = null;
const init = () => {
  AMapLoader.load({
    key: "c65d5e95b767b9985332093eb2839111", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0" // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  })
    .then(e => {
      AMap = e;
      map = new AMap.Map("container", {
        // 设置地图容器id
        pitch: 0, //倾斜度
        mapStyle: "amap://styles/darkblue", //设置地图的显示样式
        zoom: 15, // 初始化地图级别
        center: [116.397428, 39.90923] // 初始化地图中心点位置
      });
      plugin();
    })
    .catch(e => {
      console.log(e);
    });
};
// 添加自定义（瓦片）图层
// let tileLayer = new AMap.TileLayer({
//   zooms: [3, 18],
//   tileSize: 256,
//   getTileUrl: (x: number, y: number, z: number) => {
//     console.log(x, y, z);
//     return `/map/${z}/${x}/${y}.png`;
//   }
// });
// map.add(tileLayer);
// 工具插件
let toolbar = ref<any>();
let Scale = ref<any>();
let driving = ref<any>();
//"AMap.DistrictSearch"
const plugin = () => {
  AMap.plugin(["AMap.ToolBar", "AMap.Driving", "AMap.Scale"], function () {
    //异步同时加载多个插件
    toolbar.value = new AMap.ToolBar();
    map.addControl(toolbar.value);
    Scale.value = new AMap.Scale();
    map.addControl(Scale.value);
    driving.value = new AMap.Driving({
      ferry: 1, //非轮渡
      autoFitView: true,
      extensions: "all"
      // map: map,
      // panel: "panel"
    });
    drivingRoute();
  });
};
let routeList = ref<any>([
  [116.379028, 39.865042],
  [116.38828, 39.87079]
]);
// 标记点
let location = ref<any>();
let start = ref<any>();
let end = ref<any>();

const startBox = ref<HTMLDivElement>();
const endBox = ref<HTMLDivElement>();

//驾车路线规划
const drivingRoute = () => {
  driving.value.search(LngLat(routeList.value[0]), LngLat(routeList.value[1]), (status: any, result: any) => {
    // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
    console.log(result, status);
    if (status === "complete") {
      start.value = setMarker({
        position: LngLat(routeList.value[0]),
        content: startBox.value,
        anchor: "bottom-center"
      });
      map.add(start.value);
      end.value = setMarker({
        position: LngLat(routeList.value[1]),
        content: endBox.value,
        anchor: "bottom-center"
      });
      map.add(end.value);
      getData(result);
    } else {
      console.log("获取驾车数据失败");
    }
  });
};

// 画线(经过的路线)
// 此处为假数据
const getData = (result: any) => {
  result?.routes[0]?.steps.map((item: any, index: number) => {
    if (index < 3) {
      polylineList.value = polylineList.value.concat(item.path);
    }
  });
  polyline();
  if (location.value) {
    map.remove(location.value);
  }
  let position = polylineList.value[polylineList.value.length - 1];
  let marker = setMarker({
    position: position,
    icon: new URL("@/assets/images/rescue/ambulance.png", import.meta.url).href,
    size: new AMap.Size(50, 30)
  });
  location.value = marker;
  // 显示所有位中心[location.value,start.value,end.value]
  map.setFitView(null, false, [100, 50, 50, 50]);
  map.add(marker);
};
// 行驶路线
let polylineList = ref<any>([]);
let polylineData = ref<any>([]);
const polyline = () => {
  if (polylineData.value) {
    map.remove(polylineData.value);
  }
  polylineData.value = new AMap.Polyline({
    path: polylineList.value,
    strokeWeight: 5,
    strokeColor: "#1a66ff", // 线条颜色
    lineJoin: "round", // 折线拐点连接处样式
    strokeOpacity: 1,
    zIndex: 50
  });
  map.add(polylineData.value);
};

// 自定义标记
const setMarker = (data: any) => {
  return new AMap.Marker({
    icon: data?.icon,
    content: data?.content,
    size: data?.size, // 图标尺寸
    position: data.position,
    zIndex: 51,
    anchor: data.anchor || "center"
  });
};

// 位置实例
const LngLat = (data: number[]) => {
  return new AMap.LngLat(data[0], data[1]);
};

onMounted(() => {
  init();
});
onUnmounted(() => {
  map?.destroy();
});
</script>

<style scoped lang="scss">
.startMarker {
  text-align: center;
  font-size: 14px;
  color: #fff;

  .icon {
    width: 40px;
    height: 45px;
  }
}

.mapBox {
  height: 100%;
  background-image: url("../../../../assets/images/rescue/route.png");
  background-position: center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;

  .title {
    font-size: 22px;
    color: #ffffff;
    padding-bottom: 15px;
    font-weight: bold;
    display: flex;
    align-items: center;

    .icon {
      width: 25px;
      height: 25px;
      margin-right: 10px;
    }
  }
}

.MapContainer {
  position: relative;
  flex: 1;
  height: 0;

  .container {
    width: 100%;
    height: 100%;
  }
}

:deep(.amap-marker) {
  img {
    width: 100%;
    height: 100%;
  }
}

.modal {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 11;
  background: rgba(0, 0, 0, 0.8);
  width: 318px;
  font-size: 14px;
  color: #ffffff;
  line-height: 22px;
  border-radius: 8px;
  font-weight: bold;
  border-radius: 10px;
  overflow: hidden;
  padding-bottom: 10px;

  .item {
    padding: 3px 8px;
  }

  .plate {
    background: rgba(43, 140, 254, 0.2);
    padding: 0 8px;
    line-height: 31px;
    margin-bottom: 4px;
    font-size: 18px;
    color: #00d3fc;

    .icon {
      width: 24px;
      height: 24px;
    }
  }

  .label {
    width: 80px;
  }

  .value {
    flex: 1;
  }
}

.panel {
  position: fixed;
  top: 0;
  left: 0;
}
</style>
